package com.example.shiro_springboot.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Enumeration;

@Controller
public class MyController {

    @GetMapping(value = "login")
    public String login() {
        return "login";
    }

    @GetMapping("userLogin")
    @ResponseBody
    public String userLogin(String uname, String pwd, boolean remember) {
        // 获取当前登录用户的subject对象
        Subject subject = SecurityUtils.getSubject();
        AuthenticationToken token = new UsernamePasswordToken(uname, pwd, remember);
        try {
            subject.login(token);
//            return "redirect:main";
            return "登录成功！";
        } catch (ExcessiveAttemptsException e) {
            return "错误次数过多，该账号已被锁定";
        } catch (UnknownAccountException e) {
            return "用户名不存在！";
        } catch (AuthenticationException e) {
            return "账号或密码错误！";
        } catch (AuthorizationException e) {
            return "没有权限";
        }
    }

    @GetMapping("main")
    public String mainPage() {
        return "main";
    }

    //声明单元方法:获取session中的数据
    @RequestMapping("demoSession")
    @ResponseBody
    public String demoSession(HttpSession session){
        //遍历session中的数据
        Enumeration<String> names = session.getAttributeNames();
        while(names.hasMoreElements()){
            String name = names.nextElement();
            Object value = session.getAttribute(name);
            //打印结果
            System.out.println(name+"----"+value);
        }
        return "session取值";
    }
}
